package com.shopping.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

import com.shopping.config.Default;

/**
 * This class is used for ...
 * 
 * @author liuhuan
 * @version 1.0, 2013-8-31 下午11:28:17
 */
@SuppressWarnings("unchecked")
@Transactional
public abstract class BaseDaoImpl<T> implements BaseDao<T> {

	private SessionFactory sessionFactory;

	private Class<T> clazz;

	public BaseDaoImpl() {
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class<T>) pt.getActualTypeArguments()[0];

	}

	@Override
	public boolean save(T entity) {
		try {
			getSession().save(entity);
			return true;
		} catch (Exception e) {
			Default.logger.error("save faild! ", e);
			return false;
		}
	}

	@Override
	public boolean update(T entity) {
		try {
			getSession().update(entity);
			return true;
		} catch (Exception e) {
			Default.logger.error("update faild !", e);
			return false;
		}
	}

	@Override
	public boolean delete(Serializable id) {
		try {
			Object object = this.getById(id);
			getSession().delete(object);
			return true;
		} catch (Exception e) {
			Default.logger.error("delete faild !", e);
			return false;
		}
	}

	@Override
	public T getById(Serializable id) {
		if (id == null) {
			return null;
		} else {
			return (T) getSession().get(clazz, id);
		}
	}

	@Override
	public List<T> findAll() {
		return getSession().createCriteria(clazz).list();
	}

	@Override
	public Set<T> getByIds(Serializable[] ids) {

		if (ids == null || ids.length == 0) {
			return null;
		}

		List<T> list = getSession().createCriteria(clazz).add(Restrictions.in("id", ids)).list();
		return new HashSet<T>(list);
	}

	/**
	 * 获取一个可用的session
	 * 
	 * @return
	 */
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	/**
	 * get set
	 * 
	 * @return
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
